/**
 * 
 */
package com.nmc.service.comm;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author m.rathi
 *
 */
public class CommunicationGateway {
	
	public static String SUCCESS = "SUCCESS";
	public static String FAILURE = "FAILURE";
	private static final boolean SMS_ENABLED = false;
	
	enum SMS_TYPE {
		PROMOTIONAL, TRANSACTIONAL
	};
	private SMS_TYPE currentSMSConfiguration = SMS_TYPE.PROMOTIONAL;
	
	private static String SERVER_URL = "http://ctr.beyondmobile.co.in/sendhttp.php?user=%s&password=%s&mobiles=%s&message=%s&sender=%s&route=4";
	
	CommunicationConfig config = null;
	
	public CommunicationConfig getConfig() {
		return config;
	}



	public void setConfig(CommunicationConfig config) {
		this.config = config;
	}



	/*
	 * Sends sms msg to specified numbers
	 */
	public String sendSMS( String number, String msg) {
		
		if ( SMS_ENABLED) {
			
			try {
	
				//String serverURL = "http://ctr.beyondmobile.co.in/sendhttp.php?user=%s&password=%s&mobiles=%s&message=%s&sender=%s&route=4";
				String serverURL = String.format(SERVER_URL, config.getSmsApiUid(), config.getSmsApiPwd(), number , URLEncoder.encode(msg, "UTF-8"), "NMCBDR");
				if (currentSMSConfiguration == SMS_TYPE.TRANSACTIONAL) {
					serverURL += "&route=4";
				}
				URL url = new URL(serverURL);
				
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("GET");
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setUseCaches(false);
				conn.connect();
				BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = rd.readLine()) != null)
				{
					buffer.append(line).append("\n");
				}
					System.out.println(buffer.toString());
					rd.close();
					conn.disconnect();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
		}
		
		return SUCCESS;
		
	}
	
	public static void main(String argv[]) {
		CommunicationConfig c = new CommunicationConfig();
		c.setSmsApiPwd("gleam123");
		c.setSmsApiUid("gleam");
		c.setSmsApiSenderId("NMCBDR");
		CommunicationGateway cg = new CommunicationGateway();
		cg.setConfig(c);
		cg.sendSMS("9890299349", "Test MSG");
	}
	
	
	
	public String sendForgotPasswordEmail(String toEmail, String subject, String body) {
		//TODO email sending code
		return SUCCESS;
	}
	
	
	public String sendBirthNotificationEmail(String[] toEmail, String subject, String body) {
		//TODO email sending code
		return SUCCESS;
	}
	

	

}
